package com.portal.backend.controller;

import com.portal.backend.model.User;
import com.portal.backend.payload.UserProfileUpdateRequest;
import com.portal.backend.payload.UserSummary;
import com.portal.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.Collections;
import org.springframework.security.core.context.SecurityContextHolder;
import com.portal.backend.security.UserPrincipal;
import com.portal.backend.mapper.UserMapper;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.util.MultiValueMap;
import org.springframework.util.LinkedMultiValueMap;

import javax.validation.Valid;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/me")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<UserSummary> getCurrentUser() {
        UserSummary userSummary = userService.getCurrentUserSummary();
        return ResponseEntity.ok(userSummary);
    }

    @PutMapping("/me")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<UserSummary> updateCurrentUserProfile(@Valid @RequestBody UserProfileUpdateRequest profileUpdateRequest) {
        userService.updateUserProfile(profileUpdateRequest);
        // Re-fetch the summary to reflect changes
        UserSummary updatedUserSummary = userService.getCurrentUserSummary(); 
        return ResponseEntity.ok(updatedUserSummary);
    }
    
    // Endpoint to get a specific user's public profile (optional)
    @GetMapping("/{username}")
    public ResponseEntity<UserSummary> getUserProfile(@PathVariable String username) {
        // This would require a method in UserService to fetch UserSummary by username
        // For now, let's assume such a method exists or will be added if this endpoint is fully implemented.
        // UserSummary userSummary = userService.getUserSummaryByUsername(username);
        // return ResponseEntity.ok(userSummary);
        return ResponseEntity.notFound().build(); // Placeholder
    }

    @PostMapping("/avatar")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        System.out.println("[Avatar] 收到头像上传请求: " + (file != null ? file.getOriginalFilename() : "null"));
        if (file.isEmpty()) {
            System.out.println("[Avatar] 文件为空");
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        try {
            // 构造转发到文件服务器的请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileAsResource);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            String fileServerUrl = "http://106.53.88.157:8201/upload";
            ResponseEntity<String> response = restTemplate.postForEntity(fileServerUrl, requestEntity, String.class);
            if (!response.getStatusCode().is2xxSuccessful()) {
                return ResponseEntity.status(500).body("文件服务器上传失败: " + response.getBody());
            }
            // 假设文件服务器返回的body就是文件的URL
            String url = response.getBody();
            // 获取当前用户并更新avatar字段
            UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println("[Avatar] 当前用户ID: " + userPrincipal.getId());
            User user = userMapper.selectById(userPrincipal.getId());
            if (user == null) {
                System.out.println("[Avatar] 用户未找到: " + userPrincipal.getId());
                return ResponseEntity.status(404).body("用户不存在");
            }
            user.setAvatar(url);
            userMapper.updateById(user);
            System.out.println("[Avatar] 头像字段已更新: " + url);
            return ResponseEntity.ok().body(Collections.singletonMap("url", url));
        } catch (Exception e) {
            System.out.println("[Avatar] 上传失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body("上传失败: " + e.getMessage());
        }
    }
} 